<template>
  <div class="login-box">
    <div class="content">
      <div class="header">
        <img class="logo" src="../assets/images/mlogo.png" alt="" />
        <h2 class="title">新蜂商城</h2>
      </div>

      <el-form :model="ruleForm" :rules="rules" ref="formIns">
        <el-form-item label="账号" prop="account">
          <el-input
            autofocus
            placeholder="请输入手机号/用户名"
            v-model.trim="ruleForm.account"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            show-password
            v-model.trim="ruleForm.password"
            @keydown.enter.native="submit"
          ></el-input>
        </el-form-item>
        <p class="tip">
          登录表示您已同意
          <a href="javascript:;">《服务条款》</a>
        </p>
        <el-form-item>
          <el-button type="primary" :loading="confirmLoading" @click="submit">
            立即登录
          </el-button>
        </el-form-item>
        <div class="remember">
          <el-checkbox v-model="remember">记住账号和密码</el-checkbox>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import md5 from "blueimp-md5";
import _ from "@/assets/utils";
import activeRoutes from "@/router/activeRoutes";
let seat = "######";

export default {
  name: "xf-login",
  data() {
    // 校验账号规则
    const checkAccount = (_, value, callback) => {
      if (value.length === 0) {
        callback(new Error("账号不能为空!"));
        return;
      }
      let reg1 = /^[a-zA-Z0-9_-]{4,16}$/,
        reg2 = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (!reg1.test(value) && !reg2.test(value)) {
        callback(new Error("账号格式不正确!"));
        return;
      }
      callback();
    };
    // 校验密码规则
    const checkPassword = (_, value, callback) => {
      if (value.length === 0) {
        callback(new Error("密码不能为空!"));
        return;
      }
      let reg = /^[a-zA-Z0-9]{6,16}$/;
      if (!reg.test(value) && value !== seat) {
        callback(new Error("密码格式不正确!"));
        return;
      }
      callback();
    };

    return {
      ruleForm: {
        account: "",
        password: "",
      },
      rules: {
        account: [{ validator: checkAccount, trigger: "blur" }],
        password: [{ validator: checkPassword, trigger: "blur" }],
      },
      remember: true,
      confirmLoading: false,
    };
  },
  methods: {
    async submit() {
      try {
        await this.$refs.formIns.validate();
        // 表单校验通过：向服务器发送请求
        this.confirmLoading = true;
        let { account, password } = this.ruleForm;
        if (password === seat) {
          password = this.remPassword;
        } else {
          password = md5(password);
        }
        let { resultCode, data } = await this.$api.login(account, password);
        if (+resultCode === 200) {
          // 登录成功：存储Token、获取登陆者信息（存储到vuex中）、动态路由、记住账号密码、提示&跳转
          _.storage.set("tk", data);
          await this.$store.dispatch("setProfileAsync");
          await activeRoutes(this.$router);
          if (this.remember) {
            _.storage.set("remember", {
              account,
              password, //密码要存储MD5加密的
            });
          } else {
            _.storage.remove("remember");
          }
          this.$message.success("恭喜您，登录成功!");
          let { to } = this.$route.query;
          to ? this.$router.replace(to) : this.$router.push("/home");
        } else {
          // 登录失败：提示
          this.$message.error("账号密码有误，请重试!");
        }
      } catch (_) {}
      this.confirmLoading = false;
    },
  },
  created() {
    /* 
    进入组件第一件事情：把记住的账号密码放到文本框中 
      账号直接放在文本框中即可
      密码不能直接放在密码框中「因为我们存储的是MD5加密的密码」
        + 我们放的是一个占位符
          + 是用户自己不会输入的
          + 占位符需要符合表单校验规则
      点击提交按钮的时候，如果密码框获取的内容是占位符，则不要对占位符进行加密，而是把之前存储的MD5密码直接传递给服务器即可！！
    */
    let remb = _.storage.get("remember");
    if (!remb) return;
    this.ruleForm.account = remb.account;
    this.ruleForm.password = seat;
    this.remPassword = remb.password;
  },
};
</script>

<style lang="less" scoped>
.login-box {
  position: relative;
  height: 100%;

  .content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-sizing: border-box;
    width: 420px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 20px 40px 0 rgba(0, 0, 0, 0.2);
  }
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;

  .logo {
    margin-right: 20px;
    width: 100px;
    height: 100px;
  }

  .title {
    font-size: 28px;
    color: #1baeae;
    font-weight: 700;
  }
}

.el-form {
  box-sizing: border-box;
  margin: 0 auto;
  padding-bottom: 40px;
  width: 300px;

  /deep/.el-form-item__label {
    display: block;
  }

  .tip {
    line-height: 40px;
    font-size: 14px;

    a {
      color: #409eff;
    }
  }

  .el-button {
    width: 100%;
  }
}
</style>